package com.hm.health.Utils;

import android.content.Context;

import com.goodix.comsdk.errorcode.IErrorCode;
import com.goodix.http.jsonparams.response.BaseResponse;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

import rx.Emitter;
import rx.functions.Action1;

/**
 *
 * @author chenshi
 * @date 2019/5/29
 */

public class HciFileMergeAction implements Action1<Emitter<BaseResponse<Void>>> {

	private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
	private String mFilePath;
	private Context mContext;

	public HciFileMergeAction(String filePath, Context context) {
		this.mFilePath = filePath;
		this.mContext = context;
	}

	@Override
	public void call(Emitter<BaseResponse<Void>> emitter) {

		if (!HciFileHeartRateFetcher.isNeedCombineFile(mContext)) {
			if (null != emitter) {
				emitter.onCompleted();
			}
			return;
		}

		if ((null == mFilePath) || mFilePath.isEmpty()) {
			emitter.onError(new Throwable("Record is null"));
			return;
		}

		File orgFile = new File(mFilePath);
		if (!orgFile.exists()) {
			emitter.onError(new Throwable("File not find!"));
			return;
		}

		HciFileHeartRateFetcherEx fetcher = new HciFileHeartRateFetcherEx(null, mContext);
		LinkedHashMap<Long, Integer> hciHrsMap = fetcher.getAndSaveTimeAndHeartRate();
		LinkedHashMap<Long, Integer> hciHrsMapTmp = changeKeyFromMiliToSecond(hciHrsMap);
		hciHrsMap = hciHrsMapTmp;
		if (null == hciHrsMap || hciHrsMap.isEmpty()) {
			emitter.onError(new Throwable("Can't find vaild heart rate in hci file!"));
			return;
		}


		File tmpFile = new File(orgFile.getParent() + "/tmp.data");
		orgFile.renameTo(tmpFile);

		try {
			BufferedReader reader = new BufferedReader(new FileReader(tmpFile));
			BufferedWriter writer = new BufferedWriter(new FileWriter(orgFile));

			// write header
			String hciDevName = HciFileHeartRateFetcher.getHciDevice(mContext);
			writer.write(reader.readLine() + "\n");
			writer.write(reader.readLine() + "," + hciDevName + "\n");

			BaseResponse<Void> response = new BaseResponse<>(IErrorCode.SUCCESS, "",null);

			String line;
			int hciHeartRate = 0;
			int count = 0;
			while ((line = reader.readLine()) != null) {
				String time = line.split(",")[Constans.HeartRateFileColumnEnum.Time.ordinal()];
				long fileTime = mSimpleDateFormat.parse(time).getTime() / 1000;
				if (hciHrsMap.containsKey(fileTime)) {
					hciHeartRate = hciHrsMap.get(fileTime);
				}
				line = line + "," + hciHeartRate + "\n";
				writer.write(line);
				response.setTotalCount(hciHrsMap.size());
				response.setCurrentCount(count);
				emitter.onNext(response);
				count++;
			}

			reader.close();
			writer.flush();
			writer.close();
			tmpFile.delete();
			emitter.onCompleted();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			emitter.onError(e);
		} catch (IOException e) {
			e.printStackTrace();
			emitter.onError(e);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}


	private LinkedHashMap<Long, Integer> changeKeyFromMiliToSecond(LinkedHashMap<Long, Integer> hciHrsMap){
		LinkedHashMap<Long, Integer> result = new LinkedHashMap<>();
		Set<Long> keys = hciHrsMap.keySet();
		Iterator<Long> iterator = keys.iterator();
		Long time;
		while (iterator.hasNext()){
			time = iterator.next();
			result.put(time / 1000, hciHrsMap.get(time));
		}
		return result;
	}
}
